package com.itheima.demo5.ZengDemo5;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * @ClassName client
 * @Author 16799
 * @Date 2025/9/30 11:04
 * @Version 1.0
 * @Description TODO
 **/

/**
 * 为什么我自己写的有很多问题，其实思路和几乎所有的代码和黑马的都一样啊？
 * 烦
 */
public class client {
    private Scanner sc = new Scanner(System.in);
    private Socket socket;
    public static void main(String[] args) {
        try {
            client client = new client();
            client.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void start() throws Exception {
        System.out.println("---------客户端已启动----------");
        socket = new Socket("127.0.0.1",8877);

        while (true) {
            System.out.println("请输入命令：");
            System.out.println("1:注册");
            System.out.println("2.登录");
            System.out.println("请选择： ");

            String command = sc.next();
            switch (command){
                case "1":
                    register();
                    break;
                case "2":
                    login();
                    break;
                case "exit":
                    System.out.println("---成功退出系统-----");
                    socket.close();
                    break;
            }
        }

    }

    private void register() throws Exception {
        System.out.println("-----------------注册----------------");
        System.out.println("输入注册账号： ");
        String loginName = sc.next();
        System.out.println("输入注册密码： ");
        String passWord = sc.next();

        OutputStream os = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);

        dos.writeInt(1);

        dos.writeUTF(loginName);
        dos.writeUTF(passWord);

        dos.flush();

        System.out.println("-------------------接收服务端的响应-------------");
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        System.out.println(dis.readUTF());

    }

    private void login() throws Exception {
        System.out.println("---------------------登录----------------------");
        System.out.println("输入登录账号： ");
        String loginName = sc.next();
        System.out.println("输入登录密码： ");
        String passWord = sc.next();

        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
        dos.writeInt(2);

        dos.writeUTF(loginName);
        dos.writeUTF(passWord);
        dos.flush();

        System.out.println("---------------接收服务端的响应---------------------");
        DataInputStream dis = new DataInputStream(socket.getInputStream());
        System.out.println(dis.readUTF());
    }


}
